package com.zhhtech.zhh.ui.helper

import android.app.Dialog
import android.content.Context
import android.view.View
import android.view.ViewGroup
import androidx.core.view.isVisible
import androidx.fragment.app.Fragment
import androidx.fragment.app.FragmentActivity
import androidx.viewpager2.adapter.FragmentStateAdapter
import androidx.viewpager2.widget.ViewPager2
import com.google.android.material.tabs.TabLayout
import com.google.android.material.tabs.TabLayoutMediator
import com.loper7.date_time_picker.dialog.CardDatePickerDialog
import com.zhhtech.zhh.R
import com.zhhtech.zhh.databinding.ViewSoftInputBinding
import com.zhhtech.zhh.ui.ext.dp
import com.zhhtech.zhh.ui.ext.isLandscape
import com.zhhtech.zhh.ui.ext.toColor
import com.zhhtech.zhh.ui.widget.KeyboardHeightObserver
import com.zhhtech.zhh.ui.widget.KeyboardHeightProvider
import me.jessyan.autosize.utils.ScreenUtils


/**
 * TabLayout关联viewPage，适用于固定页面数量
 */
fun FragmentActivity.attachViewPager(
    tabLayout: TabLayout, viewPager: ViewPager2,
    fragments: List<FixedFragmentData>,
) {
    viewPager.offscreenPageLimit = fragments.size
    viewPager.adapter = FixedViewPagerAdapter(this, fragments)
    TabLayoutMediator(tabLayout, viewPager) { tab, position ->
        tab.text = fragments[position].tab
    }.attach()
}

data class FixedFragmentData(
    val tab: String?,
    val fragment: Fragment,
)

class FixedViewPagerAdapter(
    activity: FragmentActivity,
    private val fragments: List<FixedFragmentData>,
) : FragmentStateAdapter(activity) {

    override fun getItemCount(): Int {
        return fragments.size
    }

    override fun createFragment(position: Int): Fragment {
        return fragments[position].fragment
    }
}

/**
 * 设置支持横屏，宽度修改为屏幕一般
 */
fun <T : Dialog> T.supportLandscape(): T {
    if (context.isLandscape) {
        window?.attributes = window?.attributes?.apply {
            width = (context.resources.displayMetrics.widthPixels * (0.5)).toInt()
        }
    }
    return this
}

fun Context.datePicker(title: String, listener: ((Long) -> Unit)? = null): Lazy<CardDatePickerDialog> = lazy {
    CardDatePickerDialog.builder(this)
        .setTitle("${title}选择")
//        .setDisplayType(DateTimeConfig.YEAR,DateTimeConfig.MONTH,DateTimeConfig.DAY,DateTimeConfig.HOUR,DateTimeConfig.MIN)
        .setBackGroundModel(CardDatePickerDialog.CARD)
        .showBackNow(true)
        .setTouchHideable(false)
        .setWrapSelectorWheel(false)
        .setThemeColor(R.color.main_color.toColor())
        .showDateLabel(true)
        .showFocusDateInfo(true)
        .setOnChoose("选择", listener)
        .setOnCancel("关闭")
        .build()
}

fun FragmentActivity.softAdapter(
    viewInput: ViewSoftInputBinding,
    scrollView: View,
) {
    KeyboardHeightProvider(this, object : KeyboardHeightObserver() {
        private val offset = 2.dp
        override fun onKeyboardHeightChanged(height: Int, orientation: Int) {
            val soft = viewInput.root
            if (height > 0) {
                soft.isVisible = true
                val params: ViewGroup.MarginLayoutParams = viewInput.viewMargin.layoutParams as ViewGroup.MarginLayoutParams
                val margin = height + mVirtualBottomHeight
                params.setMargins(0, 0, 0, margin)
                soft.requestLayout()
                var visibleY = 0
                var colVisibleHeight = 0
                // 监听输入框输入法弹出
                currentFocus?.let {
                    val location = IntArray(2)
                    it.getLocationOnScreen(location)
                    colVisibleHeight = ScreenUtils.getScreenSize(it.context)[1] - location[1] - it.measuredHeight + offset
                    visibleY = height
                }
                if (colVisibleHeight > 0) {
                    soft.post {
                        if (colVisibleHeight in 1 until visibleY) {
                            scrollView.scrollBy(0, visibleY - colVisibleHeight)
                        }
                    }
                }
            } else {
                //输入法隐藏, 布局隐藏
                soft.isVisible = false
            }
        }
    })
}